package com.example.dds.tiancai;

import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import java.io.File;
import java.io.FileOutputStream;
import java.util.UUID;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import static com.example.dds.tiancai.RSAUtil.encrypt;
import static com.example.dds.tiancai.RSAUtil.loadPublicKey;

/**
 * @Author: xielc
 * @Date: 2019/12/9 14:45
 * @Version 1.0
 */
public class TianCaiTest {

    public static void main(String[] args) throws Exception {
        String desKey = "c8b3c46746f770a7";
        String publicKeyStr= "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCvBe6tl15cNgBMhWgeEKlp97JJonySqcfQZMsHkVPfk2JQga7jDw2fPs1+m71uFl9TAZsOuwQRWZXNGHdob2kuCJYVsBaK5qebRPn44KEVzd8atJyOkSl4sJpVLDZbTktd2OI7I4UL9gK4fdkGxv1N9zgmIxihMU8RuShTZrFUmwIDAQAB";
        String corporationCode = "";
        String url = "https://lb-test.tcsl.com.cn:8079/bi_proxy/api/data/v2";
        String str = "";
        System.out.println("json-------------->"+str);
        File file = File.createTempFile(String.valueOf(UUID.randomUUID()), ".zip");
        ZipOutputStream zos =  new ZipOutputStream(new FileOutputStream(file));
        //加密后压缩
        createZip(zos, Base64Utils.encode(DESUtil.encrypt(str,desKey)).getBytes("UTF-8"));
        zos.closeEntry();
        zos.close();
        String code = encrypt(loadPublicKey(publicKeyStr),corporationCode.getBytes());
        //body
        FileSystemResource resource = new FileSystemResource(file);
        MultiValueMap<String, Object> requestBody = new LinkedMultiValueMap<>();
        requestBody.add("file", resource);
        requestBody.add("corporationCode",code);
        //headers
        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.setContentType(MediaType.APPLICATION_JSON);
        requestHeaders.add("corpCode",code);
        HttpEntity<MultiValueMap> requestEntity = new HttpEntity<MultiValueMap>(requestBody, requestHeaders);
        RestTemplate rest = new RestTemplate();
        String result  = rest.postForObject(url, requestEntity, String.class);
        System.err.print("结果=>" + result);
        file.delete();
    }

    private static void createZip(ZipOutputStream zos, byte[] b) {
        try {
            zos.putNextEntry(new ZipEntry("param.txt"));
            zos.setComment("by zip test!");
            zos.write(b, 0, b.length);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
